<template>
  <div style="padding: 30px">
    <el-form ref="elForm" :model="formData" :rules="rules" size="mini" label-width="100px" label-position="left">
      <!-- 搜索区域 -->
      <el-row type="flex" justify="start" :gutter="20">
        <el-col :span="4">
          <el-form-item>
            <span slot="label" class="form-label">合同编号</span>
            <el-input v-model="formData.contractCode" placeholder="请输入合同编号" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <span slot="label" class="form-label">客户编号</span>
            <el-input v-model="formData.clientCode" placeholder="请输入客户编号" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <span slot="label" class="form-label">期望交货日期</span>
            <el-date-picker v-model="formData.expectedDeliveryDate" type="date" placeholder="选择日期" style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <span slot="label" class="form-label">项目类型</span>
            <el-select v-model="formData.projectType" placeholder="请选择" clearable style="width: 100%">
              <el-option label="在线设备数" value="在线设备数"></el-option>
              <el-option label="污水人数" value="污水人数"></el-option>
              <el-option label="建设" value="建设"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row>
        <el-col :span="8" class="btn-group">
          <el-button type="primary" @click="handleSearch" size="mini">搜索</el-button>
          <el-button type="primary" @click="handleAdd" size="mini">新增</el-button>
          <el-button type="primary" @click="handleBulkEdit" :disabled="selectedRows.length !== 1" size="mini">编辑</el-button>
          <el-button type="danger" @click="handleBulkDelete" :disabled="selectedRows.length !== 1" size="mini">删除</el-button>
          <el-button type="success" @click="handleExport" size="mini">导出</el-button>
        </el-col>
      </el-row>

      <!-- 表格显示区域 -->
      <div class="table-container">
        <el-table :data="tableData" border :height="tableHeight" style="width: 100%"
                  :header-cell-style="{'background-color': '#f5f7fa'}" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="contractCode" label="合同编号" width="120">
            <template slot-scope="scope">
              <el-button type="text" @click="showDetail('contract', scope.row)">
                {{scope.row.contractCode}}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="clientCode" label="客户编号" width="120">
            <template slot-scope="scope">
              <el-button type="text" @click="showDetail('client', scope.row)">
                {{scope.row.clientCode}}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="expectedDeliveryDate" label="期望交付日期" width="120">
            <template slot-scope="scope">
              {{formatDate(scope.row.expectedDeliveryDate)}}
            </template>
          </el-table-column>
          <el-table-column prop="projectType" label="项目类型" width="120"></el-table-column>
          <el-table-column prop="projectPeriod" label="项目周期" width="120"></el-table-column>
          <el-table-column prop="numberCount" label="人数/设备数" width="120"></el-table-column>
          <el-table-column prop="laborCost" label="用人成本" width="120"></el-table-column>
          <el-table-column prop="materials" label="所需物料" width="150"></el-table-column>
          <el-table-column prop="materialCost" label="物料成本" width="120"></el-table-column>
          <el-table-column prop="feedback" label="问题反馈" width="150"></el-table-column>
          <el-table-column prop="solution" label="解决方案" width="150"></el-table-column>
          <el-table-column prop="id" label="ID" v-if="false"></el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" :page.sync="formData.pageNum" :limit.sync="formData.pageSize"
        @pagination="getList" />
    </el-form>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%">
      <el-form :model="dialogForm" ref="dialogForm" :rules="dialogRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractCode">
              <el-input v-model="dialogForm.contractCode" :disabled="isEdit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户编号" prop="clientCode">
              <el-input v-model="dialogForm.clientCode"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="期望交付日期" prop="expectedDeliveryDate">
              <el-date-picker v-model="dialogForm.expectedDeliveryDate" type="date" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目类型" prop="projectType">
              <el-select v-model="dialogForm.projectType" placeholder="请选择">
                <el-option label="在线设备数" value="在线设备数"></el-option>
                <el-option label="污水人数" value="污水人数"></el-option>
                <el-option label="建设" value="建设"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目周期" prop="projectPeriod">
              <el-input v-model="dialogForm.projectPeriod"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人数/设备数" prop="numberCount">
              <el-input v-model="dialogForm.numberCount"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用人成本" prop="laborCost">
              <el-input v-model="dialogForm.laborCost" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料成本" prop="materialCost">
              <el-input v-model="dialogForm.materialCost" type="number"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="所需物料" prop="materials">
              <el-input type="textarea" v-model="dialogForm.materials"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="问题反馈" prop="feedback">
              <el-input type="textarea" v-model="dialogForm.feedback"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="解决方案" prop="solution">
              <el-input type="textarea" v-model="dialogForm.solution"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDialog">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog :title="detailTitle" :visible.sync="detailVisible" width="50%">
      <div v-if="detailData">
        <div v-for="(value, key) in detailData" :key="key" class="detail-item">
          <span class="detail-label">{{key}}:</span>
          <span class="detail-value">{{value}}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { add, list, update, delProject,selectDetail} from "@/api/monitor/project";
export default {

  data() {
    return {
      // 搜索表单数据
      formData: {
        contractCode: '',
        clientCode: '',
        expectedDeliveryDate: '',
        projectType: '',
        pageNum: 1,
        pageSize: 10,
      },
      // 表格数据
      tableData: [],
      total: 0,
      tableHeight: 400,
      selectedRows: [],
      // 对话框控制
      dialogVisible: false,
      dialogTitle: '新增',
      isEdit: false,
      detailVisible: false,
      detailTitle: '详情',
      // 对话框表单数据
      dialogForm: {
        contractCode: '',
        clientCode: '',
        expectedDeliveryDate: '',
        projectType: '',
        projectPeriod: '',
        numberCount: '',
        laborCost: '',
        materials: '',
        materialCost: '',
        feedback: '',
        solution: '',
        id: ''
      },
      // 用于查看详情时的数据
      detailParam:{
        type : '',
        id:''
      },
      detailData: null,
      // 表单验证规则
      rules: {
        // 可根据需要添加验证规则
      },
      // 表单验证规则
      dialogRules: {
        contractCode: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
        clientCode: [{ required: true, message: '请输入客户编号', trigger: 'blur' }],
        // 其他验证规则根据需要添加
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleSearch() {
      this.getList();
    },
    handleAdd() {
      this.dialogTitle = '新增';
      this.isEdit = false;
      this.resetDialogForm();
      this.dialogVisible = true;
    },
    handleBulkEdit() {
      if (this.selectedRows.length !== 1) {
        this.$message.warning('请选择一条记录进行编辑');
        return;
      }
      this.dialogTitle = '编辑';
      this.isEdit = true;
      this.dialogForm = { ...this.selectedRows[0] };
      this.dialogVisible = true;
    },
    handleBulkDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请至少选择一条记录进行删除');
        return;
      }else if (this.selectedRows.length >1){
        this.$message.warning('暂时不支持多挑选中删除');
        return;
      }
      this.$confirm('确定删除选中的记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        delProject(this.selectedRows[0].id).then(response => {

              if (response.code === 200) {
                this.$message.success('删除成功');
                this.getList(); // 刷新列表
              } else {
                // 如果返回的code不是200，打印错误信息
                this.$message.error(response.message || '操作失败'); // 提示错误消息
              }
            })
        // 执行删除操作
        // this.selectedRows.forEach(row => this.deleteRow(row));
      });
    },
    handleExport() {
      // 导出功能实现
      this.$message.success('导出成功');
    },
    showDetail(type, row) {
      this.detailTitle = type === 'contract' ? '合同详情' : '客户详情';
      // 请求获取细节数据并设置this.detailData
      // 查询合同详情
      if(type==='contract'){//合同查询
        this.detailParam.type=type
        this.detailParam.id=row.contractCode

      }else{//客户详情查询
        this.detailParam.type=type
        this.detailParam.id=row.clientCode
      }
      selectDetail(this.detailParam).then(response => {
            console.log(response)
            this.detailData = response.rows[0];
            this.detailVisible = true;
       });



    },


    submitDialog() {
      this.$refs.dialogForm.validate(valid => {
        console.log("区新增: " + valid);
        console.log("是否为编辑模式: " + this.isEdit);

        if (valid) {
          const submitFunction = this.isEdit ? update : add;
          // 调用对应的增/改函数并处理响应
          //时间格式转换
          this.dialogForm.expectedDeliveryDate=this.formatDate(this.dialogForm.expectedDeliveryDate)
          submitFunction(this.dialogForm)
            .then(response => {
              console.log("服务器响应: ", response); // 输出服务器返回的完整响应


              if (response.code === 200) {
                this.$message.success(this.isEdit ? '修改成功' : '新增成功');
                this.dialogVisible = false;
                this.getList(); // 刷新列表
              } else {
                // 如果返回的code不是200，打印错误信息
                this.$message.error(response.message || '操作111失败'); // 提示错误消息
              }
            })
            .catch(error => {
              console.error("提交失败：", error); // 捕获并打印错误信息
              this.$message.error('操作失败，请重试。'); // 友好的错误提示给用户
            });
        } else {
          this.$message.warning('表单验证失败，请检查输入项。'); // 处理验证失败的情况
        }
      });
    },
    getList() {
      this.loading = true;
      console.log("this.formData=")
      //时间格式转换
      this.formData.expectedDeliveryDate=this.formatDate(this.formData.expectedDeliveryDate)

      console.log(this.formData)
      list(this.formData).then(response => {
        this.tableData = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    addRow() {
      // 新增记录
      this.tableData.push({ ...this.dialogForm });
      this.$message.success('新增成功');
    },
    updateRow() {
      // 更新记录
      const index = this.tableData.findIndex((item) => item.contractCode === this.dialogForm.contractCode);
      if (index !== -1) {
        this.tableData.splice(index, 1, { ...this.dialogForm });
        this.$message.success('更新成功');
      }
    },
    deleteRow(row) {
      // 删除记录
      this.tableData = this.tableData.filter((item) => item.contractCode !== row.contractCode);
      this.$message.success('删除成功');
    },
    resetDialogForm() {
      this.dialogForm = {
        contractCode: '',
        clientCode: '',
        expectedDeliveryDate: '',
        projectType: '',
        projectPeriod: '',
        numberCount: '',
        laborCost: '',
        materials: '',
        materialCost: '',
        feedback: '',
        solution: '',
      };
    },
    formatDate(date) {
      return date ? new Date(date).toLocaleDateString() : '';
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    }
  },
};
</script>

<style scoped>
.table-container {
  margin-top: 20px;
}

.btn-group {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  text-align: right;
}

.detail-item {
  margin-bottom: 10px;
}

.detail-label {
  font-weight: bold;
}

.detail-value {
  margin-left: 10px;
}
.hide-column {
    display: none;  /* 不占位置，完全隐藏 */
}
</style>
